<template>
  <div class="create-order-container">
    <div class="page-header">
      <h2>创建新订单</h2>
    </div>

    <el-form :model="orderForm" label-width="120px" :rules="rules" ref="orderFormRef" class="order-form">
      <!-- 寄件人和收件人信息部分 -->
      <el-row :gutter="20">
        <!-- 左侧：寄件人信息 -->
        <el-col :span="12">
          <SenderInfo
            v-model="senderData"
            :region-options="regionOptions"
            :has-address-book="addressBookList.length > 0"
            @show-address-book="showAddressBook"
            @region-change="handleSenderRegionChange"
          />
        </el-col>
        
        <!-- 右侧：收件人信息 -->
        <el-col :span="12">
          <RecipientInfo
            v-model="recipientData"
            :region-options="regionOptions"
            :has-address-book="addressBookList.length > 0"
            @show-address-book="showAddressBook"
            @region-change="handleRecipientRegionChange"
          />
        </el-col>
      </el-row>
      
      <!-- 物品信息与运费计算 -->
      <el-row :gutter="20">
        <!-- 物品信息 -->
        <el-col :span="12">
          <ItemInfo
            v-model="itemData"
            @volume-change="calculateFreight"
            @weight-change="calculateFreight"
          />
        </el-col>
        
        <!-- 运费计算 -->
        <el-col :span="12">
          <FreightInfo
            v-model="freightData"
            :show-distance-info="showDistanceInfo"
            :sender-full-address="getFullSenderAddress()"
            :recipient-full-address="getFullRecipientAddress()"
            :estimated-distance="estimatedDistance"
            :base-freight="baseFreight"
            :weight-surcharge="weightSurcharge"
            :insurance-fee="insuranceFee"
            :service-surcharge="serviceSurcharge"
            @service-change="calculateFreight"
          />
        </el-col>
      </el-row>
      
      <div class="form-actions">
        <el-button type="primary" @click="submitOrder">创建订单</el-button>
        <el-button @click="resetForm">重置表单</el-button>
      </div>
    </el-form>
    
    <!-- 地址簿选择对话框 -->
    <AddressBookDialog
      v-model="addressBookVisible"
      :address-book-list="addressBookList"
      @select-address="selectAddress"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { userApi, type DeliveryOrderRequest } from '@/api/user'
import { useRoute } from 'vue-router'
import SenderInfo from './components/SenderInfo.vue'
import RecipientInfo from './components/RecipientInfo.vue'
import ItemInfo from './components/ItemInfo.vue'
import FreightInfo from './components/FreightInfo.vue'
import AddressBookDialog from './components/AddressBookDialog.vue'

const route = useRoute()
const orderFormRef = ref<FormInstance>()

// 分离的数据对象
const senderData = reactive({
  senderName: '',
  senderPhone: '',
  senderRegion: [] as string[],
  senderAddress: ''
})

const recipientData = reactive({
  recipientName: '',
  recipientPhone: '',
  recipientRegion: [] as string[],
  recipientAddress: ''
})

const itemData = reactive({
  itemType: '',
  weight: 1.0,
  length: 0,
  width: 0,
  height: 0,
  volume: 0,
  declaredValue: 0,
  remark: ''
})

const freightData = reactive({
  serviceType: 'standard',
  additionalServices: [] as string[],
  freight: 0,
  paymentMethod: 'online'
})

// 合并的订单表单数据（用于表单验证）
const orderForm = computed(() => ({
  ...senderData,
  ...recipientData,
  ...itemData,
  ...freightData
}))

// 表单验证规则
const rules = {
  senderName: [{ required: true, message: '请输入寄件人姓名', trigger: 'blur' }],
  senderPhone: [
    { required: true, message: '请输入寄件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  senderRegion: [{ required: true, message: '请选择寄件省市区', trigger: 'change' }],
  senderAddress: [{ required: true, message: '请输入寄件详细地址', trigger: 'blur' }],
  
  recipientName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  recipientPhone: [
    { required: true, message: '请输入收件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  recipientRegion: [{ required: true, message: '请选择收件省市区', trigger: 'change' }],
  recipientAddress: [{ required: true, message: '请输入收件详细地址', trigger: 'blur' }],
  
  itemType: [{ required: true, message: '请选择物品类型', trigger: 'change' }],
  weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
  serviceType: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
}

// 省市区数据
const regionOptions = [
  {
    value: '北京',
    label: '北京',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '朝阳区', label: '朝阳区' },
          { value: '海淀区', label: '海淀区' },
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' }
        ]
      }
    ]
  },
  {
    value: '上海',
    label: '上海',
    children: [
      {
        value: '上海市',
        label: '上海市',
        children: [
          { value: '浦东新区', label: '浦东新区' },
          { value: '黄浦区', label: '黄浦区' },
          { value: '徐汇区', label: '徐汇区' },
          { value: '长宁区', label: '长宁区' }
        ]
      }
    ]
  },
  {
    value: '广东',
    label: '广东',
    children: [
      {
        value: '广州市',
        label: '广州市',
        children: [
          { value: '天河区', label: '天河区' },
          { value: '海珠区', label: '海珠区' },
          { value: '越秀区', label: '越秀区' }
        ]
      },
      {
        value: '深圳市',
        label: '深圳市',
        children: [
          { value: '南山区', label: '南山区' },
          { value: '福田区', label: '福田区' },
          { value: '罗湖区', label: '罗湖区' }
        ]
      }
    ]
  }
]

// 地址簿相关
const addressBookVisible = ref(false)
const currentAddressType = ref('')
const addressBookList = [
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    region: ['北京', '北京市', '朝阳区'],
    address: '北京市朝阳区建国路88号'
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139002',
    region: ['上海', '上海市', '浦东新区'],
    address: '上海市浦东新区张江高科技园区'
  },
  {
    id: 3,
    name: '王五',
    phone: '13700137003',
    region: ['广东', '广州市', '天河区'],
    address: '广州市天河区天河路385号'
  }
]

// 运费计算相关变量
const baseFreight = ref(0)
const weightSurcharge = ref(0)
const insuranceFee = ref(0)
const serviceSurcharge = ref(0)
const estimatedDistance = ref(0)

// 显示地址簿
const showAddressBook = (type: string) => {
  currentAddressType.value = type
  addressBookVisible.value = true
}

// 选择地址
const selectAddress = (row: any) => {
  if (currentAddressType.value === 'sender') {
    Object.assign(senderData, {
      senderName: row.name,
      senderPhone: row.phone,
      senderRegion: row.region,
      senderAddress: row.address
    })
  } else if (currentAddressType.value === 'recipient') {
    Object.assign(recipientData, {
      recipientName: row.name,
      recipientPhone: row.phone,
      recipientRegion: row.region,
      recipientAddress: row.address
    })
  }
  addressBookVisible.value = false
  calculateFreight()
}

// 获取完整寄件地址
const getFullSenderAddress = () => {
  if (senderData.senderRegion && senderData.senderRegion.length === 3) {
    return `${senderData.senderRegion[0]}${senderData.senderRegion[1]}${senderData.senderRegion[2]}`
  }
  return ''
}

// 获取完整收件地址
const getFullRecipientAddress = () => {
  if (recipientData.recipientRegion && recipientData.recipientRegion.length === 3) {
    return `${recipientData.recipientRegion[0]}${recipientData.recipientRegion[1]}${recipientData.recipientRegion[2]}`
  }
  return ''
}

// 是否显示距离信息
const showDistanceInfo = computed(() => {
  return senderData.senderRegion.length === 3 && recipientData.recipientRegion.length === 3
})

// 寄件地址变更处理
const handleSenderRegionChange = () => {
  calculateDistance()
  calculateFreight()
}

// 收件地址变更处理
const handleRecipientRegionChange = () => {
  calculateDistance()
  calculateFreight()
}

// 计算距离（简化版，实际应调用地图API）
const calculateDistance = () => {
  if (!showDistanceInfo.value) return
  
  const senderProvince = senderData.senderRegion[0]
  const recipientProvince = recipientData.recipientRegion[0]
  
  if (senderProvince === recipientProvince) {
    const senderCity = senderData.senderRegion[1]
    const recipientCity = recipientData.recipientRegion[1]
    
    if (senderCity === recipientCity) {
      estimatedDistance.value = Math.floor(Math.random() * 20) + 10
    } else {
      estimatedDistance.value = Math.floor(Math.random() * 250) + 50
    }
  } else {
    estimatedDistance.value = Math.floor(Math.random() * 1700) + 300
  }
}

// 计算运费
const calculateFreight = () => {
  if (!showDistanceInfo.value) {
    freightData.freight = 0
    baseFreight.value = 0
    weightSurcharge.value = 0
    insuranceFee.value = 0
    serviceSurcharge.value = 0
    return
  }
  
  // 计算基础运费
  let baseFee = 0
  if (estimatedDistance.value <= 30) {
    baseFee = 10
  } else if (estimatedDistance.value <= 300) {
    baseFee = 15 + (estimatedDistance.value - 30) * 0.1
  } else {
    baseFee = 42 + (estimatedDistance.value - 300) * 0.08
  }
  
  // 根据服务类型调整基础运费
  switch (freightData.serviceType) {
    case 'express':
      baseFee *= 1.5
      break
    case 'economy':
      baseFee *= 0.8
      break
  }
  baseFreight.value = Math.round(baseFee * 100) / 100
  
  // 计算重量附加费
  const weightLimit = 1
  const volumeWeight = itemData.volume / 6000
  const chargeableWeight = Math.max(itemData.weight, volumeWeight)
  
  if (chargeableWeight > weightLimit) {
    switch (freightData.serviceType) {
      case 'express':
        weightSurcharge.value = (chargeableWeight - weightLimit) * 10
        break
      case 'standard':
        weightSurcharge.value = (chargeableWeight - weightLimit) * 6
        break
      case 'economy':
        weightSurcharge.value = (chargeableWeight - weightLimit) * 4
        break
    }
  } else {
    weightSurcharge.value = 0
  }
  weightSurcharge.value = Math.round(weightSurcharge.value * 100) / 100
  
  // 计算保价费
  if (itemData.declaredValue > 0) {
    insuranceFee.value = Math.ceil(itemData.declaredValue / 1000) * 3
  } else {
    insuranceFee.value = 0
  }
  
  // 计算增值服务费
  serviceSurcharge.value = 0
  if (freightData.additionalServices.includes('signatureRequired')) {
    serviceSurcharge.value += 5
  }
  if (freightData.additionalServices.includes('smsNotification')) {
    serviceSurcharge.value += 3
  }
  if (freightData.additionalServices.includes('priorityHandling')) {
    serviceSurcharge.value += 10
  }
  
  // 计算总运费
  freightData.freight = baseFreight.value + weightSurcharge.value + insuranceFee.value + serviceSurcharge.value
  freightData.freight = Math.round(freightData.freight * 100) / 100
}

// 提交订单
const submitOrder = async () => {
  if (!orderFormRef.value) return
  
  await orderFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        const senderFullAddress = senderData.senderRegion.join('') + senderData.senderAddress
        const receiverFullAddress = recipientData.recipientRegion.join('') + recipientData.recipientAddress
        
        const orderData: DeliveryOrderRequest = {
          senderName: senderData.senderName,
          senderPhone: senderData.senderPhone,
          senderAddress: senderFullAddress,
          receiverName: recipientData.recipientName,
          receiverPhone: recipientData.recipientPhone,
          receiverAddress: receiverFullAddress,
          itemWeight: Number(itemData.weight),
          itemVolume: Number(itemData.volume),
          itemType: itemData.itemType,
          insuredValue: Number(itemData.declaredValue),
          baseFee: Number(baseFreight.value || 0),
          weightFee: Number(weightSurcharge.value || 0),
          serviceFee: Number(serviceSurcharge.value || 0),
          insuranceFee: Number(insuranceFee.value || 0),
          totalFee: Number((baseFreight.value + weightSurcharge.value + insuranceFee.value + serviceSurcharge.value) || 0),
          remark: itemData.remark,
          paymentMethod: freightData.paymentMethod
        }
        
        console.log('提交订单数据:', orderData)
        
        const response = await userApi.createDeliveryOrder(orderData)
        
        if (response && response.code === 200) {
          ElMessage.success(response.message || '订单创建成功')
          resetForm()
        } else {
          ElMessage.error(response?.message || '订单创建失败')
        }
      } catch (error) {
        console.error('创建订单失败:', error)
        let errorMessage = '订单创建失败'
        
        if (error && typeof error === 'object' && 'message' in error) {
          errorMessage = (error as any).message
        } else if (error && typeof error === 'object' && 'msg' in error) {
          errorMessage = (error as any).msg
        }
        
        ElMessage.error(errorMessage)
      }
    } else {
      console.log('验证未通过:', fields)
      ElMessage.error('请完善必填信息')
    }
  })
}

// 重置表单
const resetForm = () => {
  if (orderFormRef.value) {
    orderFormRef.value.resetFields()
    Object.assign(senderData, {
      senderName: '',
      senderPhone: '',
      senderRegion: [],
      senderAddress: ''
    })
    Object.assign(recipientData, {
      recipientName: '',
      recipientPhone: '',
      recipientRegion: [],
      recipientAddress: ''
    })
    Object.assign(itemData, {
      itemType: '',
      weight: 1.0,
      length: 0,
      width: 0,
      height: 0,
      volume: 0,
      declaredValue: 0,
      remark: ''
    })
    Object.assign(freightData, {
      serviceType: 'standard',
      additionalServices: [],
      freight: 0,
      paymentMethod: 'online'
    })
    calculateFreight()
  }
}

// 解析完整地址，提取省市区和详细地址
const parseFullAddress = (fullAddress: string) => {
  const findMatchingRegion = (address: string, options: any[]) => {
    const result = []
    let remainingAddress = address
    
    console.log('开始解析地址:', address)
    
    // 查找省份
    for (const province of options) {
      const provinceLabel = province.label
      const provinceValue = province.value
      
      // 检查地址是否包含省份名称
      if (remainingAddress.includes(provinceLabel) || remainingAddress.includes(provinceValue)) {
        result.push(provinceValue)
        console.log('匹配到省份:', provinceValue)
        
        // 更精确的字符串替换：找到最长匹配
        let matchedProvinceName = ''
        if (remainingAddress.includes(provinceLabel)) {
          matchedProvinceName = provinceLabel
        } else if (remainingAddress.includes(provinceValue)) {
          matchedProvinceName = provinceValue
        }
        
        // 从地址开头移除省份名称
        const provinceIndex = remainingAddress.indexOf(matchedProvinceName)
        if (provinceIndex === 0) {
          remainingAddress = remainingAddress.substring(matchedProvinceName.length)
        }
        
        console.log('移除省份后的地址:', remainingAddress)
        
        // 查找城市
        if (province.children) {
          for (const city of province.children) {
            const cityLabel = city.label
            const cityValue = city.value
            
            if (remainingAddress.includes(cityLabel) || remainingAddress.includes(cityValue)) {
              result.push(cityValue)
              console.log('匹配到城市:', cityValue)
              
              // 更精确的字符串替换
              let matchedCityName = ''
              if (remainingAddress.includes(cityLabel)) {
                matchedCityName = cityLabel
              } else if (remainingAddress.includes(cityValue)) {
                matchedCityName = cityValue
              }
              
              // 从地址开头移除城市名称
              const cityIndex = remainingAddress.indexOf(matchedCityName)
              if (cityIndex === 0) {
                remainingAddress = remainingAddress.substring(matchedCityName.length)
              }
              
              console.log('移除城市后的地址:', remainingAddress)
              
              // 查找区县
              if (city.children) {
                for (const district of city.children) {
                  const districtLabel = district.label
                  const districtValue = district.value
                  
                  if (remainingAddress.includes(districtLabel) || remainingAddress.includes(districtValue)) {
                    result.push(districtValue)
                    console.log('匹配到区县:', districtValue)
                    
                    // 更精确的字符串替换
                    let matchedDistrictName = ''
                    if (remainingAddress.includes(districtLabel)) {
                      matchedDistrictName = districtLabel
                    } else if (remainingAddress.includes(districtValue)) {
                      matchedDistrictName = districtValue
                    }
                    
                    // 从地址开头移除区县名称
                    const districtIndex = remainingAddress.indexOf(matchedDistrictName)
                    if (districtIndex === 0) {
                      remainingAddress = remainingAddress.substring(matchedDistrictName.length)
                    }
                    
                    console.log('移除区县后的地址:', remainingAddress)
                    break
                  }
                }
              }
              break
            }
          }
        }
        break
      }
    }
    
    console.log('最终解析结果 - 省市区:', result, '详细地址:', remainingAddress.trim())
    
    return {
      region: result,
      detailAddress: remainingAddress.trim()
    }
  }
  
  return findMatchingRegion(fullAddress, regionOptions)
}

// 处理来自常用地址的预填充数据
const handleQueryParams = () => {
  const { name, phone, address } = route.query
  
  if (name && phone && address) {
    console.log('检测到常用地址参数:', { name, phone, address })
    
    // 解析完整地址
    const { region, detailAddress } = parseFullAddress(address as string)
    
    console.log('解析出的省市区:', region)
    console.log('解析出的详细地址:', detailAddress)
    
    // 预填充寄件人信息
    Object.assign(senderData, {
      senderName: name as string,
      senderPhone: phone as string,
      senderRegion: region,
      senderAddress: detailAddress
    })
    
    console.log('预填充后的寄件人数据:', senderData)
    
    // 触发地区变更事件，计算距离
    if (region.length === 3) {
      handleSenderRegionChange()
    }
    
    ElMessage.success('已自动填入常用地址信息')
  }
}

onMounted(() => {
  calculateFreight()
  handleQueryParams() // 处理query参数
})
</script>

<style scoped>
.create-order-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.order-form {
  margin-bottom: 40px;
}

/* 添加flex布局确保卡片高度一致 */
.order-form .el-row {
  display: flex;
  align-items: stretch;
}

.order-form .el-col {
  display: flex;
  flex-direction: column;
}

/* 确保卡片填满整个列高度 */
.order-form .el-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.order-form .el-card .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 确保表单项在卡片内正确分布 */
.form-card {
  margin-bottom: 20px;
  height: 100%;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .order-form :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 8px;
  }
  
  .order-form :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
  
  /* 移动端取消flex布局，避免高度问题 */
  .order-form .el-row {
    display: block;
  }
  
  .order-form .el-col {
    display: block;
  }
  
  .order-form .el-card {
    height: auto;
    display: block;
  }
}
</style>